package com.ruitu.arad.api.okhttp.builder;

import android.content.Context;

import com.ruitu.arad.api.okhttp.MyOkHttp;
import com.ruitu.arad.api.okhttp.callback.MyCallback;
import com.ruitu.arad.api.okhttp.response.IResponseHandler;
import com.ruitu.arad.api.okhttp.util.LogUtils;

import java.util.Map;

import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.Request;
import okhttp3.RequestBody;

/**
 * patch builder
 * Created by tsy on 16/12/06.
 */
public class PatchBuilder extends OkHttpRequestBuilderHasParam<PatchBuilder> {

    public PatchBuilder(MyOkHttp myOkHttp) {
        super(myOkHttp);
    }

    @Override
    public void enqueue(Context context, final IResponseHandler responseHandler) {
        try {
            if (mUrl == null || mUrl.length() == 0) {
                throw new IllegalArgumentException("url can not be null !");
            }
//            mUrl = appendParams(mUrl, mParams);

            Request.Builder builder = new Request.Builder().url(mUrl);
            appendHeaders(builder, context);

            builder.addHeader("Content-Type", "application/json");
            builder.addHeader("Accept", "application/json");
            builder.addHeader("Accept-Charset", "utf-8");
            builder.addHeader("Charset", "utf-8");
            if (mTag != null) {
                builder.tag(mTag);
            }
            if (mJsonParams.length() > 0) {      //上传json格式参数
                RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), mJsonParams);
                builder.patch(body);

            } else {
                builder.patch(RequestBody.create(MediaType.parse("text/plain;charset=utf-8"), ""));
            }
            Request request = builder.build();

            mMyOkHttp.getOkHttpClient()
                    .newCall(request)
                    .enqueue(new MyCallback(context, responseHandler));

        } catch (Exception e) {
            LogUtils.e("Patch enqueue error:" + e.getMessage());
            responseHandler.onFailure(0, e.getMessage());
        }
    }


    //append params to form builder
    private void appendParams(FormBody.Builder builder, Map<String, String> params) {

        if (params != null && !params.isEmpty()) {
            for (String key : params.keySet()) {
                builder.add(key, params.get(key));
            }
        }
    }

    //append params to url
    private String appendParams(String url, Map<String, String> params) {
        StringBuilder sb = new StringBuilder();
        sb.append(url + "?");
        if (params != null && !params.isEmpty()) {
            for (String key : params.keySet()) {
                sb.append(key).append("=").append(params.get(key)).append("&");
            }
        }

        sb = sb.deleteCharAt(sb.length() - 1);
        return sb.toString();
    }
}
